import cv2
import numpy as np
from ctypes import windll
import time
import tkinter as tk
from tkinter import messagebox
import threading

# 加载预训练的分类器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# 打开摄像头
cap = cv2.VideoCapture(0)

# 设置屏幕锁定函数
def lock_screen():
    user32 = windll.User32
    user32.LockWorkStation()

# 创建假锁屏窗口
def create_fake_lockscreen(timeout=1200):  # 将超时时间更改为20分钟
    def close_window():
        password = e1.get()
        if password == "1":  # 这里设置解锁密码
            w.quit()  # 使用 quit 来退出主循环
        else:
            error_label.config(text="密码错误！")

    def on_timeout():
        nonlocal running
        if running:  # 检查是否还在运行
            lock_screen()
            running = False  # 设置运行标志为 False
            w.quit()  # 退出主循环

    running = True  # 初始化运行标志
    w = tk.Tk()
    w.attributes('-fullscreen', True)
    w.attributes('-alpha', 0.5)  # 设置透明度

    tk.Label(w, text="密码：", font=("楷体", 60)).pack()
    e1 = tk.Entry(w, show="*", font=("楷体", 60))
    e1.pack()
    tk.Button(w, text=" 确 定 ", font=("楷体", 60), command=close_window).pack()
    error_label = tk.Label(w, text="", font=("楷体", 20), fg="red")
    error_label.pack()

    # 设置定时器
    timer = threading.Timer(timeout, on_timeout)
    timer.start()

    # 阻止关闭窗口
    w.protocol("WM_DELETE_WINDOW", lambda: None)

    # 启动主循环
    while running and w.winfo_exists():
        try:
            w.update_idletasks()
            w.update()
        except tk.TclError:
            break  # 如果窗口被销毁，则退出循环

    # 取消定时器以防它已经启动但还未触发
    if timer.is_alive():
        timer.cancel()

    # 销毁窗口
    w.destroy()

# 主循环
unlocked = False
while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=1)

    if len(faces) > 0 and not unlocked:
        print("人脸检测到，解锁屏幕")
        unlocked = True
    elif len(faces) == 0 and unlocked:
        print("无人脸，锁定屏幕")
        create_fake_lockscreen()  # 显示假锁屏，并在超时后真锁屏
        unlocked = False

# 清理资源
cap.release()
cv2.destroyAllWindows()
